package com.fowo.api.syncAmazon.core.sync;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fowo.api.entity.AmzAdvertisAuthInfo;
import com.fowo.api.entity.ShopInfo;
import com.fowo.api.service.impl.AmzAdvertisAuthInfoServiceImpl;
import com.fowo.api.syncAmazon.core.AbstractAmzAdSyncData;
import com.fowo.api.syncAmazon.core.model.RequestConfigurationModel;
import com.fowo.api.syncAmazon.core.model.SPRequestParamModel;
import com.fowo.api.syncAmazon.entity.ApiDefine;
import com.fowo.api.syncAmazon.entity.AmazonSpAdvertisedProductReport;
import com.fowo.api.syncAmazon.entity.TmpAmazonSpAdvertisedProductReport;
import com.fowo.api.syncAmazon.service.TmpAmazonSpAdvertisedProductReportService;
import com.fowo.api.syncAmazon.util.AdColumnsUtil;
import com.fowo.api.syncAmazon.util.AdProductEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @fileName: AdvertisReportSync
 * @Description: 代码目的，作用，如何工作
 * @Author: yyf
 * @Date: 2024/3/5 0005 13:29
 */
@Component
public class SpAdvertisedProductReportSync extends AbstractAmzAdSyncData {
    @Resource
    private TmpAmazonSpAdvertisedProductReportService tmpSpAdvertisedProductReportService;
    @Resource
    private AmzAdvertisAuthInfoServiceImpl amzAdvertisAuthInfoService;
    private static final String REPORT_TYPE_ID = "spAdvertisedProduct";
    private ApiDefine apiDefine = ApiDefine.builder()
            .apiCode(REPORT_TYPE_ID)
            .initdate(30)
            .timeInterval(10)
            .timeIntervalType("day").build();
    @Override
    protected ApiDefine setApiDefine() {
        return apiDefine;
    }

    @Override
    protected void requestData() throws Exception {
        logger.info("获取授权信息--全量");
        List<AmzAdvertisAuthInfo> amzAdvertInfo = amzAdvertisAuthInfoService.list();
        Map<String, List<AmzAdvertisAuthInfo>> byRefreshToken = amzAdvertInfo.stream()
                .collect(Collectors.groupingBy(AmzAdvertisAuthInfo::getRefreshToken));
        logger.info("获取要查询的字段及类型");
        // 排除不能请求报告的字段
        String[] columnsToRemove = {"id","sid","innerlid","serialVersionUID"};
        List<String> columns = AdColumnsUtil.getColumns(AmazonSpAdvertisedProductReport.class,columnsToRemove);

        // 清空临时表
        tmpSpAdvertisedProductReportService.deleteAll();

        byRefreshToken.forEach((key,value) -> {
            for (AmzAdvertisAuthInfo amzAdvertisAuthInfo : value) {
                ShopInfo shop = shopInfoServiceImpl.getById(amzAdvertisAuthInfo.getSid());
                if(shop == null){
                    continue;
                }
                logger.info("正在获取店铺："+shop.getId()+"报告");
                JSONArray res = null;
                try {
                    res = getByShop(amzAdvertisAuthInfo, columns);
                    download(res,shop);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    public JSONArray getByShop(AmzAdvertisAuthInfo amzAdvertisAuthInfo, List<String> columns) throws Exception {
        // 请求头
        Map<String, Object> headers = this.getHeaders(amzAdvertisAuthInfo);
        // 请求参数
        SPRequestParamModel params = new SPRequestParamModel();
        params.setName(REPORT_TYPE_ID+" Report"+startTime+"-"+endTime);
        params.setStartDate(startTime);
        params.setEndDate(endTime);

        RequestConfigurationModel configuration = new RequestConfigurationModel();
        configuration.setAdProduct(AdProductEnum.PRODUCTS.getValue());

        List<String> groupBy = new ArrayList<>();
        groupBy.add("advertiser");
        configuration.setGroupBy(groupBy);
        // 需要查询的字段
        configuration.setColumns(columns);
        // 报告id
        configuration.setReportTypeId(REPORT_TYPE_ID);
        // 统计维度明细或摘要
        configuration.setTimeUnit(TIME_UNIT);

        configuration.setFormat(FORMAT);
        params.setConfiguration(configuration);

        // 创建报告
        String reportId = this.createReport(params, headers);
        // 检查报告
        String reportUrl = this.checkReport(reportId, headers);
        // 下载报告
        JSONArray res = getAndUnzipReport(reportUrl);
        return res;
    }

    @Override
    protected <T> void download(T param, ShopInfo shop) throws IOException, IllegalArgumentException {
        JSONArray res = null;
        if (param instanceof JSONArray){
            try {
                res = (JSONArray) param;
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }

        int size = res.size();
        List<TmpAmazonSpAdvertisedProductReport> list = new ArrayList<>(size);
        for (Object o : res) {
            JSONObject tmp = JSONObject.parseObject(o.toString());
            logger.info("将获取到的数据转成java对象，还剩："+size--);
            TmpAmazonSpAdvertisedProductReport tmpSpAdvertisedProductReport = tmp.toJavaObject(TmpAmazonSpAdvertisedProductReport.class);
            tmpSpAdvertisedProductReport.setSid(shop.getId());
            list.add(tmpSpAdvertisedProductReport);
        }
        logger.info("正在缓存店铺："+shop.getId()+"的数据");
        tmpSpAdvertisedProductReportService.saveBatch(list);
    }

    @Override
    protected void updateOrInsertData() {
        logger.info("正在更新数据至正式表");
        tmpSpAdvertisedProductReportService.insertOrUpdate();
        logger.info("正在更新innerLId");
        tmpSpAdvertisedProductReportService.updateInnerLid();
    }
}
